<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线编程助手</title>
    <script src="https://cdn.jsdelivr.net/npm/mermaid@10.6.1/dist/mermaid.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/styles/github.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/highlight.js@11.9.0/highlight.min.js"></script>
    <style>
        body {
            padding: 20px;
            background-color: #f5f5f5;
        }
        .problem-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .editor-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .chat-section {
            background: white;
            padding: 20px;
            border-radius: 8px;
            height: calc(100vh - 40px);
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        #problemDescription {
            height: 200px;
            overflow-y: auto;
        }
        #codeEditor {
            width: 100%;
            height: 300px;
            font-family: monospace;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            resize: vertical;
        }
        #chatOutput {
            height: calc(100vh - 200px);
            overflow-y: auto;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 10px;
            margin-bottom: 10px;
            background: #f8f9fa;
        }
        #chatOutput pre {
            background: #fff;
            padding: 10px;
            border-radius: 4px;
            border: 1px solid #e0e0e0;
            margin: 10px 0;
        }
        #chatOutput code {
            font-family: monospace;
            background: #f8f9fa;
            padding: 2px 4px;
            border-radius: 3px;
        }
        .test-case {
            background: #f8f9fa;
            padding: 10px;
            margin: 5px 0;
            border-radius: 4px;
            cursor: pointer;
        }
        .test-case:hover {
            background: #e9ecef;
        }
        .status-badge {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 14px;
            z-index: 1000;
        }
        .connected {
            background-color: #28a745;
            color: white;
        }
        .disconnected {
            background-color: #dc3545;
            color: white;
        }
        .mermaid {
            background: white;
            padding: 10px;
            border-radius: 4px;
            margin: 10px 0;
        }
        .message {
            margin-bottom: 15px;
            padding: 10px;
            border-radius: 8px;
        }
        .user-message {
            background: #e3f2fd;
            margin-left: 20%;
            margin-right: 10px;
        }
        .ai-message {
            background: #f5f5f5;
            margin-right: 20%;
            margin-left: 10px;
        }
        .message-content {
            margin-top: 5px;
        }
        .message-header {
            font-size: 0.9em;
            color: #666;
            margin-bottom: 5px;
        }
    </style>
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 左侧：题目描述和代码编辑器 -->
            <div class="col-md-8">
                <div class="problem-section">
                    <h4>题目描述</h4>
                    <div id="problemDescription"></div>
                    <div class="mt-3">
                        <h5>测试用例</h5>
                        <div id="testCases"></div>
                    </div>
                </div>
                <div class="editor-section">
                    <div class="form-group">
                        <textarea id="codeEditor" spellcheck="false"></textarea>
                    </div>
                    <div class="mt-3">
                        <div id="testCases"></div>
                    </div>
                </div>
            </div>
            <!-- 右侧：AI助手对话 -->
            <div class="col-md-4">
                <div class="chat-section">
                    <h4>AI助手</h4>
                    <div id="chatOutput"></div>
                    <div class="input-group">
                        <input type="text" id="userInput" class="form-control" placeholder="输入你的问题...">
                        <button class="btn btn-primary" onclick="sendMessage()">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div id="statusBadge" class="status-badge disconnected">未连接</div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 初始化 Mermaid
        mermaid.initialize({
            startOnLoad: true,
            theme: 'default',
            flowchart: {
                useMaxWidth: true,
                htmlLabels: true,
                curve: 'basis'
            },
            securityLevel: 'loose'
        });

        // 初始化 Marked
        marked.setOptions({
            highlight: function(code, lang) {
                const language = hljs.getLanguage(lang) ? lang : 'plaintext';
                return hljs.highlight(code, { language }).value;
            },
            langPrefix: 'hljs language-'
        });

        let currentMessageContent = '';
        let currentMessageDiv = null;

        // 测试用例数据
        const testProblems = [
            {
                title: "两数之和",
                description: `给定一个整数数组 nums 和一个整数目标值 target，请你在该数组中找出和为目标值 target 的那两个整数，并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是，数组中同一个元素在答案里不能重复出现。`,
                testCases: [
                    { input: "nums = [2,7,11,15], target = 9", output: "[0,1]" },
                    { input: "nums = [3,2,4], target = 6", output: "[1,2]" }
                ],
                template: `def twoSum(nums, target):
    # 在这里写入你的代码
    pass`
            },
            {
                title: "反转字符串",
                description: `编写一个函数，其作用是将输入的字符串反转过来。输入字符串以字符数组 s 的形式给出。
不要给另外的数组分配额外的空间，你必须原地修改输入数组、使用 O(1) 的额外空间解决这一问题。`,
                testCases: [
                    { input: '["h","e","l","l","o"]', output: '["o","l","l","e","h"]' },
                    { input: '["H","a","n","n","a","h"]', output: '["h","a","n","n","a","H"]' }
                ],
                template: `def reverseString(s):
    # 在这里写入你的代码
    pass`
            }
        ];

        let currentProblem = 0;
        let currentEventSource = null;

        // 初始化页面
        function initializePage() {
            loadProblem(currentProblem);
            updateStatus(false);
        }

        // 加载题目
        function loadProblem(index) {
            const problem = testProblems[index];
            document.getElementById('problemDescription').innerHTML = `
                <h3>${problem.title}</h3>
                <p>${problem.description}</p>
            `;
            
            const testCasesHtml = problem.testCases.map((testCase, idx) => `
                <div class="test-case" onclick="loadTestCase(${idx})">
                    <strong>测试用例 ${idx + 1}</strong><br>
                    输入: ${testCase.input}<br>
                    输出: ${testCase.output}
                </div>
            `).join('');
            
            document.getElementById('testCases').innerHTML = testCasesHtml;
            document.getElementById('codeEditor').value = problem.template;
        }

        // 加载测试用例到编辑器
        function loadTestCase(index) {
            const problem = testProblems[currentProblem];
            const testCase = problem.testCases[index];
            // 这里可以根据需要处理测试用例的加载
        }

        // 发送到AI并处理响应
        function sendToAI(query) {
            if (currentEventSource) {
                currentEventSource.close();
            }

            // 获取当前题目和代码信息
            const problem = testProblems[currentProblem];
            console.log("Problem object:", problem);  
            const code = document.getElementById('codeEditor').value;
            
            // 构建请求参数
            const params = new URLSearchParams();
            params.append('query', query);
            params.append('problem_content', problem.title + "\n" + problem.description);
            console.log("Sending problem_content:", problem.title + "\n" + problem.description);  
            params.append('editor_code', code);

            appendMessage('用户', query);
            
            const eventSource = new EventSource(`http://localhost:8001/process/stream?${params.toString()}`);
            currentEventSource = eventSource;

            eventSource.onopen = () => {
                updateStatus(true);
            };

            eventSource.onmessage = (event) => {
                const data = JSON.parse(event.data);
                handleAIResponse(data);
            };

            eventSource.onerror = (error) => {
                console.error('EventSource failed:', error);
                updateStatus(false);
                eventSource.close();
            };
        }

        // 发送消息给AI
        function sendMessage() {
            const input = document.getElementById('userInput');
            const query = input.value.trim();
            if (query) {
                sendToAI(query);
                input.value = '';
            }
        }

        // 监听输入框的回车事件
        document.getElementById('userInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });

        // 处理AI响应
        function handleAIResponse(data) {
            const chatOutput = document.getElementById('chatOutput');
            
            if (data.error) {
                appendMessage('AI', `<div style="color: red;">错误: ${data.error}</div>`, true);
                currentEventSource.close();
                updateStatus(false);
                return;
            }
            
            if (data.chunk === '[DONE]') {
                currentEventSource.close();
                updateStatus(false);
                currentMessageContent = '';
                currentMessageDiv = null;
                return;
            }

            if (!currentMessageDiv) {
                // 创建新的消息div
                currentMessageDiv = document.createElement('div');
                currentMessageDiv.className = 'message ai-message';
                
                const headerDiv = document.createElement('div');
                headerDiv.className = 'message-header';
                headerDiv.textContent = 'AI助手';
                currentMessageDiv.appendChild(headerDiv);
                
                const contentDiv = document.createElement('div');
                contentDiv.className = 'message-content';
                currentMessageDiv.appendChild(contentDiv);
                
                chatOutput.appendChild(currentMessageDiv);
            }

            // 更新消息内容
            currentMessageContent += data.chunk;
            const contentDiv = currentMessageDiv.querySelector('.message-content');
            
            // 检查是否有完整的Mermaid代码块
            const matches = currentMessageContent.match(/```mermaid\n([\s\S]*?)```/g);
            if (matches) {
                // 先用marked渲染整个内容
                contentDiv.innerHTML = marked.parse(currentMessageContent);
                
                // 找到所有完整的mermaid代码块并渲染
                contentDiv.querySelectorAll('code.language-mermaid').forEach(code => {
                    const div = document.createElement('div');
                    div.className = 'mermaid';
                    div.textContent = code.textContent;
                    code.parentNode.replaceWith(div);
                    
                    try {
                        mermaid.render(`mermaid-${Date.now()}`, div.textContent).then(({svg}) => {
                            div.innerHTML = svg;
                        }).catch(err => {
                            console.error('Mermaid渲染错误:', err);
                            div.innerHTML = `<div style="color: red;">渲染错误: ${err.message}</div>`;
                        });
                    } catch (err) {
                        console.error('Mermaid渲染错误:', err);
                        div.innerHTML = `<div style="color: red;">渲染错误: ${err.message}</div>`;
                    }
                });
            } else {
                // 没有完整的Mermaid代码块，直接渲染为Markdown
                contentDiv.innerHTML = marked.parse(currentMessageContent);
            }
            
            chatOutput.scrollTop = chatOutput.scrollHeight;
        }

        // 添加用户消息到聊天窗口
        function appendMessage(sender, content, isHtml = false) {
            if (sender === 'AI') return; // AI消息由handleAIResponse处理
            
            const chatOutput = document.getElementById('chatOutput');
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${sender === 'AI' ? 'ai-message' : 'user-message'}`;
            
            const headerDiv = document.createElement('div');
            headerDiv.className = 'message-header';
            headerDiv.textContent = sender === 'AI' ? 'AI助手' : '用户';
            messageDiv.appendChild(headerDiv);
            
            const contentDiv = document.createElement('div');
            contentDiv.className = 'message-content';
            if (isHtml) {
                contentDiv.innerHTML = content;
            } else {
                contentDiv.textContent = content;
            }
            messageDiv.appendChild(contentDiv);
            
            chatOutput.appendChild(messageDiv);
            chatOutput.scrollTop = chatOutput.scrollHeight;
        }

        // 切换题目
        function switchProblem(delta) {
            const newIndex = currentProblem + delta;
            if (newIndex >= 0 && newIndex < testProblems.length) {
                currentProblem = newIndex;
                loadProblem(currentProblem);
            }
        }

        // 更新连接状态
        function updateStatus(connected) {
            const badge = document.getElementById('statusBadge');
            badge.className = `status-badge ${connected ? 'connected' : 'disconnected'}`;
            badge.textContent = connected ? '已连接' : '未连接';
        }

        // 初始化页面
        window.onload = initializePage;
    </script>
</body>
</html>
